"use client"

import { useRef, useState, useEffect } from "react"
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Animated } from "react-native"
import { Volume2, CheckCircle2, XCircle } from "lucide-react-native"
import { theme } from "../../constants/theme"

interface LetterSpellCardProps {
    word: string
    phonetic: string
    meaning?: string
    showHint: boolean
    onPlaySound: () => void
    onCheckAnswer: (isCorrect: boolean) => void
    onNext: () => void
}

export function LetterSpellCard({
    word,
    phonetic,
    meaning,
    showHint,
    onPlaySound,
    onCheckAnswer,
    onNext,
}: LetterSpellCardProps) {
    const [userInput, setUserInput] = useState("")
    const [feedbackState, setFeedbackState] = useState<"none" | "correct" | "incorrect">("none")
    const [isPlaying, setIsPlaying] = useState(false)
    const inputRef = useRef<TextInput>(null)

    // 动画值
    const feedbackOpacity = useRef(new Animated.Value(0)).current
    const successScale = useRef(new Animated.Value(1)).current
    const cardOpacity = useRef(new Animated.Value(1)).current

    // 修改onNext函数，添加动画效果
    const handleNextWithAnimation = () => {
        // 添加淡出动画
        Animated.timing(cardOpacity, {
            toValue: 0,
            duration: 250,
            useNativeDriver: true,
        }).start(() => {
            onNext()
            // 淡入动画会在父组件中处理
        })
    }

    // 检查答案
    const checkAnswer = () => {
        const isCorrect = userInput.trim().toLowerCase() === word.toLowerCase()

        if (isCorrect) {
            setFeedbackState("correct")
            Animated.sequence([
                Animated.timing(feedbackOpacity, {
                    toValue: 1,
                    duration: 300,
                    useNativeDriver: true,
                }),
                Animated.timing(successScale, {
                    toValue: 1.2,
                    duration: 200,
                    useNativeDriver: true,
                }),
                Animated.timing(successScale, {
                    toValue: 1,
                    duration: 200,
                    useNativeDriver: true,
                }),
            ]).start()

            // 延迟后自动进入下一个单词
            setTimeout(() => {
                onCheckAnswer(true)
                handleNextWithAnimation()
            }, 1500)
        } else {
            setFeedbackState("incorrect")
            Animated.timing(feedbackOpacity, {
                toValue: 1,
                duration: 300,
                useNativeDriver: true,
            }).start()

            // 延迟后隐藏错误反馈
            setTimeout(() => {
                Animated.timing(feedbackOpacity, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }).start(() => {
                    setFeedbackState("none")
                    onCheckAnswer(false)
                })
            }, 1500)
        }
    }

    // 播放发音
    const playSound = () => {
        if (isPlaying) return
        setIsPlaying(true)
        onPlaySound()
        // 模拟播放完成
        setTimeout(() => {
            setIsPlaying(false)
        }, 1000)
    }

    // 当showHint变化时更新输入框
    useEffect(() => {
        if (showHint) {
            setUserInput(word)
        }
    }, [showHint, word])

    // 自动聚焦到输入框
    useEffect(() => {
        const timer = setTimeout(() => {
            inputRef.current?.focus()
        }, 500)

        return () => clearTimeout(timer)
    }, [])

    // 重置状态
    useEffect(() => {
        setUserInput(showHint ? word : "")
        setFeedbackState("none")
        feedbackOpacity.setValue(0)
        successScale.setValue(1)

        // 自动聚焦到输入框
        setTimeout(() => {
            inputRef.current?.focus()
        }, 100)
    }, [word, showHint])

    // 将容器View改为Animated.View，并添加opacity动画
    return (
        <Animated.View style={[styles.container, { opacity: cardOpacity }]}>
          

            {/* 输入框 */}
            <View style={styles.inputContainer}>
                <TextInput
                    ref={inputRef}
                    style={[styles.input, showHint && styles.inputHighlighted]}
                    value={userInput}
                    onChangeText={setUserInput}
                    placeholder="输入单词拼写..."
                    placeholderTextColor={theme.colors.neutral.gray}
                    autoCapitalize="none"
                    autoCorrect={false}
                    onSubmitEditing={checkAnswer}
                    returnKeyType="done"
                    editable={!showHint}
                />
            </View>
            <Text style={styles.phonetic}>{phonetic}</Text>
            <View style={styles.wordInfo}>
                {meaning && <Text style={styles.meaning}>{meaning}</Text>}
                <TouchableOpacity style={styles.soundButton} onPress={playSound} disabled={isPlaying}>
                    <Volume2 size={24} color={theme.colors.primary.default} />
                </TouchableOpacity>
            </View>
            {/* 确定按钮 */}
            <View style={styles.confirmButtonContainer}>
                <TouchableOpacity style={styles.confirmButton} onPress={checkAnswer}>
                    <Text style={styles.confirmButtonText}>确定</Text>
                </TouchableOpacity>
            </View>

            {/* 反馈区域 */}
            <View style={styles.feedbackContainer}>
                {feedbackState === "correct" && (
                    <Animated.View
                        style={[styles.feedbackContent, { opacity: feedbackOpacity, transform: [{ scale: successScale }] }]}
                    >
                        <CheckCircle2 size={24} color={theme.colors.secondary.green.default} />
                        <Text style={styles.feedbackTextSuccess}>正确!</Text>
                    </Animated.View>
                )}
                {feedbackState === "incorrect" && (
                    <Animated.View style={[styles.feedbackContent, { opacity: feedbackOpacity }]}>
                        <XCircle size={24} color={theme.colors.secondary.red.default} />
                        <Text style={styles.feedbackTextError}>错误，请重试</Text>
                    </Animated.View>
                )}
            </View>

            {/* 预留空间 */}
            <View style={styles.reservedSpace}></View>
        </Animated.View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: "100%",
        alignItems: "center",
        paddingTop: 20,
    },
    inputContainer: {
        marginTop: theme.spacing.lg,
        marginBottom: theme.spacing.md,
        alignItems: "center",
        width: "100%",
    },
    input: {
        width: "100%",
        borderBottomWidth: 2,
        borderBottomColor: theme.colors.primary.light,
        paddingVertical: theme.spacing.md,
        fontSize: theme.fontSize.xl,
        color: theme.colors.neutral.black,
        textAlign: "center",
        fontWeight: theme.fontWeight.medium,
    },
    inputHighlighted: {
        borderBottomColor: theme.colors.primary.default,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.bold,
    },
    confirmButtonContainer: {
        alignItems: "center",
        marginBottom: theme.spacing.md,
        marginTop: theme.spacing.md,
    },
    confirmButton: {
        paddingHorizontal: theme.spacing.xl,
        paddingVertical: theme.spacing.md,
        backgroundColor: theme.colors.primary.default,
        borderRadius: theme.borderRadius.medium,
    },
    confirmButtonText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.white,
    },
    feedbackContainer: {
        height: 40,
        justifyContent: "center",
        alignItems: "center",
        marginBottom: theme.spacing.md,
    },
    feedbackContent: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
    },
    feedbackTextSuccess: {
        marginLeft: theme.spacing.sm,
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.secondary.green.default,
    },
    feedbackTextError: {
        marginLeft: theme.spacing.sm,
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.secondary.red.default,
    },
    wordInfo: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        marginTop: theme.spacing.md,
        marginBottom: theme.spacing.md,
    },
    meaning: {
        fontSize: theme.fontSize.lg,
        color: theme.colors.neutral.black,
        marginRight: theme.spacing.md,
    },
    phonetic: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        marginRight: theme.spacing.md,
    },
    soundButton: {
        width: 44,
        height: 44,
        borderRadius: 22,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
    },
    reservedSpace: {
        flex: 1,
    },
})

